package com.geeker.framework.security.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.geeker.common.api.CommonResult;
import com.geeker.common.core.domain.AccessUser;
import com.geeker.common.core.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入前置拦截器");
        AccessUser accessUser = tokenService.getAccessUser();
        if (accessUser != null) {
            tokenService.verifyToken(accessUser);
            return true;
        }
        print(response,"您没有权限访问！请先登录.");
        return false;
    }

    protected void print(HttpServletResponse response,String message) throws Exception {
        /**
         * 设置响应头
         */
        response.setHeader("Content-Type","application/json");
        response.setCharacterEncoding("UTF-8");
        String result = new ObjectMapper().writeValueAsString(CommonResult.forbidden(message));
        response.getWriter().print(result);
    }
}
